package edu.ustb.efws.base.service;

import edu.ustb.efws.BaseException;
import edu.ustb.efws.base.domain.Position;
import edu.ustb.efws.base.mapper.PositionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 风险点设置业务服务
 *
 * @author TS Group
 */
@Service
@Transactional(readOnly = true)
public class PositionService {
    private final PositionMapper mapper;

    @Autowired
    public PositionService(PositionMapper mapper) {
        this.mapper = mapper;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public Position save(Position t){
        if(mapper.countPoint(t.getIptId(), t.getThoId()) > 0){
            throw new BaseException("测量点已经设置");
        }
        Date now = new Date();
        t.setCreateTime(now);
        t.setUpdateTime(now);
        mapper.insert(t);
        return t;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public Position update(Position t){
        if(mapper.countPoint(t.getIptId(), t.getThoId()) > 0){
            throw new BaseException("测量点已经设置");
        }
        if(mapper.update(t) == 0){
            throw new BaseException("修改设置失败");
        }
        return mapper.findOne(t.getId());
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean delete(int id){
        return mapper.delete(id) > 0;
    }

    public Position get(int id){
        Position t = mapper.findOne(id);
        if(t == null){
            throw new BaseException("删除设置失败");
        }
        return t;
    }

    public List<Position> all(){
        return mapper.findAll();
    }

    public List<Position> queryIn(List<Integer> ids) {
        return mapper.findIn(ids);
    }

    public long count(String outNumber, String area, String position){
        return mapper.count(outNumber, area, position);
    }

    public List<Position> query(String outNumber, String area, String position, int offset, int limit){
        return mapper.find(outNumber, area, position, offset, limit);
    }
}
